package cn.tedu.ximart.server.service.impl;

import cn.tedu.ximart.server.constant.CommonConst;
import cn.tedu.ximart.server.ex.ServiceException;
import cn.tedu.ximart.server.mapper.AlbumMapper;
import cn.tedu.ximart.server.mapper.PictureMapper;
import cn.tedu.ximart.server.pojo.dto.PictureAddNewDTO;
import cn.tedu.ximart.server.pojo.entity.Picture;
import cn.tedu.ximart.server.pojo.vo.AlbumDetailVO;
import cn.tedu.ximart.server.service.IPictureService;
import cn.tedu.ximart.server.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author HCL
 */
@Slf4j
@Service
public class PictureServiceImpl implements IPictureService {

    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private AlbumMapper albumMapper;

    @Override
    public void addNew(PictureAddNewDTO pictureAddNewDTO) {
        log.debug("准备开始处理增加图片的业务，参数：{}", pictureAddNewDTO);
        //检查URL是否存在(图片的url应该唯一)
        String url = pictureAddNewDTO.getUrl();
        int count = pictureMapper.countByUrl(url);
        if (count > 0) {
            String message = "增加图片失败，图片url:【" + url + "】已经被占用";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        //检查相册是否存在
        Long albumId = pictureAddNewDTO.getAlbumId();
        AlbumDetailVO album = albumMapper.getById(albumId);
        if (album == null) {
            String message = "新增图片失败,选择的相册不存在,可能已删除!";
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        //处理相册默认封面(如果相册为空,则将新建的图片设为相册的封面)
        int pictureCountOfAlbum = pictureMapper.countByAlbumId(albumId);
        int cover = pictureCountOfAlbum == 0 ? 1 : 0;
        Integer sort = pictureAddNewDTO.getSort();

        //执行增加图片
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureAddNewDTO, picture);
        picture.setIsCover(cover);
        //为sort字段赋值,使其不为空
        picture.setSort(sort == null ? CommonConst.SORT_DEFAULT : sort);
        int rows = pictureMapper.insert(picture);
        if (rows != 1) {
            String message = "增加图片失败，服务器繁忙，请稍后再试";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void deleteById(Long id) {
        int rows = pictureMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除图片失败，id为：" + id + "的图片不存在";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }


    }
}
